<?php


namespace CbjCode\General\Library\DesignVue\src\components;

/**
 * Class StringFormat
 * @property $fields
 * @property $content
 */
class StringFormat
{
    static $instance;

    private $fields = [];

    protected $content;

    public function __construct(array $fields = [])
    {
        $this->fields = $fields;
        $this->getContent();
    }

    /**
     * @param array $fields
     * @return StringFormat|string
     */
    public static function make(array $fields = []){
        $self = self::$instance;
        if (!$self instanceof self) {
            $self = new static($fields);
        }
        return $self->content;
    }

    /**
     * @return string
     */
    public function getContent(){
        $this->content = '[';
        foreach ($this->fields as $key=>$field){
            unset($field->origins['search']);
            $this->content .= $this->parseChild($key,$field->origins);
        }
        $this->content .= ']';
        return $this->content;
    }

    /**
     * @param string $field_key
     * @param string|array $field_value
     * @return string
     */
    public function parseChild(string $field_key = '', $field_value = ''){
        if (is_array($field_value)){
            if (count($field_value) == count($field_value, 1)) {
                //一维数组
                $html = '{';
                foreach ($field_value as $key=>$value){
                    if ($value!=null){
                        $html .= $this->parseChild($key,$value);
                    }
                }
                $html .= '},';
            }else{
                // 多维数组
                $html = '[';
                foreach ($field_value as $key=>$field){
                    $html .= $this->parseChild($key,$field);
                }
                $html .= '],';
            }
        }else{
            $html = $field_key.":'".$field_value."',";
        }
        return $html;
    }


    /**
     * 防止实例被克隆
     */
    public function __clone()
    {
        // TODO: Implement __clone() method.
    }

    /**
     * 防止反序列化（这将创建它的副本）
     */
    public function __wakeup()
    {
        // TODO: Implement __wakeup() method.
    }

}